package bancosys.tec.rtm.impl.diagnostician;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import bancosys.tec.rtm.diagnostician.AbstractDiagnostician;
import bancosys.tec.rtm.diagnostician.DiagnosisBean;

/**
 * Cria um diagnostico com a versao e revisao dos 'jars' marcados com SNAPSHOT, se disponiveis. Usa informacoes do plugin do maven
 * build-info.
 * 
 * @author takeshi
 */
public class SnapshotVersionDiagnostician extends AbstractDiagnostician {

    /**
     * {@inheritDoc}
     */
    public String getName() {
        return "Versão de componentes SNAPSHOT";
    }
    
    /**
     * Extrai o nome do pacote
     * 
     * @param url the raw url
     * @return string
     */
    private static String extractPackageName(String url) {
        String substring = url.substring(url.lastIndexOf('/') + 1);
        final int i = 3;
        return substring.substring(0, substring.length() - i);
    }

    /**
     * @param packageName o nome do pacote
     * @return Properties
     */
    public Properties findPropertiesFor(String packageName) {
        Matcher matcher = this.filePattern.matcher(packageName);
        if (matcher.matches()) {
            String artifactId = matcher.group(1);
            Properties props = new Properties();
            try {
                final InputStream res =
                        Thread.currentThread().getContextClassLoader().getResourceAsStream("buildInfo-" + artifactId + ".properties");
                if (res == null) {
                    return null;
                }
                props.load(res);
                return props;
            } catch (IOException e) {
                return null;
            }
        }
        return null;
    }

    private final Pattern filePattern = Pattern.compile("(.+)-[\\d.]+-SNAPSHOT.+");

    /**
     * {@inheritDoc}
     * 
     * @see bancosys.tec.rtm.diagnostician.AbstractDiagnostician#fillDiagnosisBean(bancosys.tec.rtm.diagnostician.DiagnosisBean)
     */
    @Override
    protected boolean fillDiagnosisBean(DiagnosisBean bean) throws Exception {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        if (contextClassLoader instanceof URLClassLoader) {
            URL[] ls = ((URLClassLoader) contextClassLoader).getURLs();
            for (URL url : ls) {
                final String file = url.getFile();
                if (file.contains("SNAPSHOT") && file.contains("/")) {
                    final String pack = extractPackageName(url.toString());
                    Properties props = this.findPropertiesFor(pack);
                    if (props != null) {
                        bean.addDescription(pack + ": ver:" + props.getProperty("version", "none") + "rev: "
                                + props.getProperty("revision", "not available"));
                    } else {
                        bean.addDescription(pack + ": not available");
                    }
                }
            }
            return true;
        } else {
            bean.addDescription("ContextClassLoader não é um URLClassLoader.");
            return false;
        }
    }
}
